package com.xudow.app.ui.user;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.activeshare.edu.ucenter.models.order.AgencyOrderDetail;
import com.xudow.app.R;
import com.xudow.app.ui.BaseActivity;
import com.xudow.app.ui.PayActivity;
import com.xudow.app.ui.task.OrderDeleteTask;
import com.xudow.app.ui.task.OrderDetailTask;
import com.xudow.app.ui.task.OrderListTask;
import com.xudow.app.ui.widget.XViewPager;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 我的订单Activity
 *
 * @author lukecheng
 */
public class OrdersActivity extends BaseActivity implements DataUpdateListener {

    /**
     * 订单状态
     * 0：未付款 1：已付款 2：已删除 3：已过期
     */
    public static final int ORDER_STATUS_ALL = -1;
    public static final int ORDER_STATUS_UNPAY = 0;
    public static final int ORDER_STATUS_PAID = 1;
    public static final int ORDER_STATUS_DELETED = 2;
    public static final int ORDER_STATUS_EXPIRED = 3;

    private static final int NUM_ITEMS = 3;

    private SectionsPagerAdapter pagerAdapter;
    private XViewPager viewPager;

    private OrderListFragment[] fragments;

    private TextView paidTab, allTab, tobepayTab;

    private List<AgencyOrderDetail> orders;

    private OrderListTask orderListTask;

    private int currentTabIndex = 1;
    List<Long> listtime=new ArrayList<Long>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_orders);

        paidTab = (TextView) findViewById(R.id.paid_tab);
        allTab = (TextView) findViewById(R.id.all_tab);
        tobepayTab = (TextView) findViewById(R.id.to_be_pay_tab);
        currentTabIndex=getIntent().getIntExtra("orderstate",1);
        fragments = new OrderListFragment[NUM_ITEMS];
        for (int i = 0; i < NUM_ITEMS; i++) {
            fragments[i] = OrderListFragment.newInstance(i);
            fragments[i].setDataUpdateListener(this);
        }

        pagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
        viewPager = (XViewPager) findViewById(R.id.viewpager);
        viewPager.setEnableScroll(false);
        viewPager.setAdapter(pagerAdapter);

        viewPager.setCurrentItem(currentTabIndex);
        changeTabSelectionState(currentTabIndex);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {

                viewPager.setCurrentItem(position);
                changeTabSelectionState(position);

                setFragmentOrders();
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();

    }
    Handler handler=new Handler();
    private void initData(){
        orderListTask = new OrderListTask(this, orderListTaskHandler);
        addTask(orderListTask);
        orderListTask.execute();

    }
    /**
     * 设置不同tab的数据
     */
    private void setFragmentOrders() {
        if (null == orders) {
            return;
        }

        int position = currentTabIndex;

        int currentStatus = ORDER_STATUS_ALL;

        if (0 == position) {
            currentStatus = ORDER_STATUS_PAID;
        } else if (2 == position) {
            currentStatus = ORDER_STATUS_UNPAY;
        }

        List<AgencyOrderDetail> sorder = new ArrayList<AgencyOrderDetail>();
        for (AgencyOrderDetail ard : orders) {
            if (ORDER_STATUS_ALL == currentStatus) {
                sorder.add(ard);
            } else if (ard.getStatus() == currentStatus) {
                sorder.add(ard);
            } else if (ard.getStatus() == currentStatus) {
                sorder.add(ard);
            }
        }

        fragments[position].setOrders(sorder);
    }

    /**
     * 获取订单列表Handler
     */
    private Handler orderListTaskHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            if (OrderListTask.SUCCESS == msg.what) {
                orders = new ArrayList<AgencyOrderDetail>();
                AgencyOrderDetail[] orderArr = (AgencyOrderDetail[]) msg.getData().getSerializable("orders");

                orders.addAll(Arrays.asList(orderArr));
                Date now=new Date();

                for(int i=0;i<orders.size();i++){


                    long oncreatetime=orders.get(i).getCreateTime().getTime();
                    long xianzaitime=now.getTime();
                    long sx=xianzaitime-oncreatetime;

                    if(1800000>sx){
                        listtime.add(sx);
                    }
                    Collections.sort(listtime, new Comparator<Long>() {
                        @Override
                        public int compare(Long o1, Long o2) {
                            if (o1.longValue() < o2.longValue())
                                return 1;
                            if (o1.longValue() > o2.longValue())
                                return -1;
                            return 0;
                        }
                    });

                }
                if(listtime.size()>0){
                //三十分钟之后重新访问数据，更新UI
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        orderListTask = new OrderListTask(OrdersActivity.this, orderListTaskHandler);
                        addTask(orderListTask);
                        orderListTask.execute();
                    }
                }, listtime.get(0));
                }
                setFragmentOrders();

            }
        }
    };

    private void changeTabSelectionState(int position) {
        currentTabIndex = position;

        paidTab.setBackgroundResource(0);
        paidTab.setTextColor(getResources().getColor(R.color.text_medium));
        allTab.setBackgroundResource(0);
        allTab.setTextColor(getResources().getColor(R.color.text_medium));
        tobepayTab.setBackgroundResource(0);
        tobepayTab.setTextColor(getResources().getColor(R.color.text_medium));

        switch (position) {
            case 0:
                //paidTab.setBackgroundResource(R.mipmap.tab_selected_bottom_border);
                paidTab.setTextColor(getResources().getColor(R.color.rvcode));
                break;
            case 1:
                //allTab.setBackgroundResource(R.mipmap.tab_selected_bottom_border);
                allTab.setTextColor(getResources().getColor(R.color.rvcode));
                break;
            case 2:
                //tobepayTab.setBackgroundResource(R.mipmap.tab_selected_bottom_border);
                tobepayTab.setTextColor(getResources().getColor(R.color.rvcode));
                break;
            default:
                break;
        }
    }

    public void onBackBtnClick(View view) {
        finish();
    }

    public void onTabClick(View view) {
        int index = 0;

        switch (view.getId()) {
            case R.id.paid_tab:
                index = 0;
                break;
            case R.id.all_tab:
                index = 1;
                break;
            case R.id.to_be_pay_tab:
                index = 2;
                break;
        }

        changeTabSelectionState(index);
        viewPager.setCurrentItem(index);

        setFragmentOrders();
    }

    @Override
    public void onDelete(AgencyOrderDetail orderDetail) {

        for (int i = 0; i < orders.size(); i++) {
            if (orderDetail.getId() == orders.get(i).getId()) {
                orders.remove(i);
                break;
            }
        }
        HashMap<String, String> pramers = new HashMap<String, String>();
        pramers.put("order_id", orderDetail.getId()+"");
        OrderDeleteTask detailtask = new OrderDeleteTask(this, detailHandler);
        addTask(detailtask);
        detailtask.execute(pramers);
        showLodingDialog("正在取消订单");
        orders.remove(orderDetail);
    }

    private Handler detailHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            hideLoadingDialog();
            if (msg.what==OrderDetailTask.SUCCESS){
                getMyApp().makeToast("成功取消订单");
                initData();
            }else
                getMyApp().makeToast("操作失败");
        }
    };

    @Override
    public void onPay(AgencyOrderDetail orderDetail) {
        Intent intent=new Intent(this,PayActivity.class);
        intent.putExtra("orderPrice", orderDetail.getTotalPrice()+"");
        intent.putExtra("orderId",orderDetail.getId());
        startActivity(intent);
    }

    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return fragments[position];
        }

        @Override
        public int getCount() {
            return NUM_ITEMS;
        }
    }

}
